package com.xm.myapplication.MVP.A.View;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.fm.openinstall.OpenInstall;
import com.fm.openinstall.listener.AppInstallAdapter;
import com.fm.openinstall.listener.AppWakeUpAdapter;
import com.fm.openinstall.model.AppData;
import com.google.android.material.appbar.AppBarLayout;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.xm.httpapi.BaseView.BaseMVPActivity;
import com.xm.myapplication.MVP.A.IDemo;
import com.xm.myapplication.MVP.A.Model.LoginResult;
import com.xm.myapplication.MVP.A.Model.PwdLoginRequest;
import com.xm.myapplication.MVP.A.Presenter.Presenter;
import com.xm.myapplication.R;
import com.xm.myapplication.Util.AppDownloadManager;
import com.xm.myapplication.Util.ImageUtil;
import com.xm.myapplication.Util.Utils;
import com.xm.myapplication.View.LoadingImageView;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;


public class MVPActivity extends BaseMVPActivity<Presenter, MVPActivity> implements IDemo.IView, AppBarLayout.OnOffsetChangedListener {
    @BindView(R.id.rv_tab1)
    public RecyclerView rvList;
    private DemoAdapter demoAdapter;
    private List<String> list = new ArrayList<>();
    private List<LocalMedia> selectList = new ArrayList<>();

    @BindView(R.id.tv_take_photo)
    public TextView tvTakePhoto;

    @BindView(R.id.iv_photo)
    public ImageView iv_photo;


    /**
     * 大布局背景，遮罩层
     */
    @BindView(R.id.bg_content)
    public View bgContent;

    @BindView(R.id.app_bar)
    public AppBarLayout appBar;
    /**
     * 展开状态下toolbar显示的内容
     */

//    @BindView(R.id.include_toolbar_open)
//    public View toolbarOpen;
    /**
     * 展开状态下toolbar的遮罩层
     */

//    @BindView(R.id.bg_toolbar_open)
//    public View bgToolbarOpen;
    /**
     * 收缩状态下toolbar显示的内容
     */
    @BindView(R.id.include_toolbar_close)
    public View toolbarClose;

    /**
     * 收缩状态下toolbar的遮罩层
     */
    @BindView(R.id.bg_toolbar_close)
    public View bgToolbarClose;

    @BindView(R.id.loading)
    LoadingImageView mLoadingImageView;

    @BindView(R.id.tv_onclick)
    TextView tv_onclick;

    // 8.0未知应用
    public static final int INSTALL_PACKAGES_REQUESTCODE = 1112;

    public static final int GET_UNKNOWN_APP_SOURCES = 1113;


    @BindView(R.id.iv)
    ImageView imageView;

    AppDownloadManager mDownloadManager;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        init();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 此处要调用，否则App在后台运行时，会无法截获
        OpenInstall.getWakeUp(intent, wakeUpAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    if (PictureSelector.obtainMultipleResult(data).get(0) != null) {
                        // 图片选择结果回调
                        LocalMedia localMedia = PictureSelector.obtainMultipleResult(data).get(0);
                        if (localMedia.isCompressed()) {
                            String albumPath = localMedia.getCompressPath();
                            //设置图片圆角角度
                            RoundedCorners roundedCorners = new RoundedCorners(30);
                            //通过RequestOptions扩展功能
                            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(50, 50)
                                    //圆形
                                    .circleCrop();
                            Glide.with(MVPActivity.this)
                                    .load(albumPath).apply(options).into(iv_photo);

                            Glide.with(MVPActivity.this)
                                    .load(albumPath).apply(options).into(mLoadingImageView);

                        }
                    }

                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        wakeUpAdapter = null;
    }

    private void moveleft(int duration, float px) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "translationX", px);
        animator.setDuration(duration);
        animator.start();
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //imageView.setAlpha(0.5f);
            }
        });
    }

    private void moveAlpha(int duration, float from, float to) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "alpha", from, to);
        animator.setDuration(duration);
        animator.start();
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //imageView.setAlpha(0.5f);
            }
        });
    }

    private void move0(int duration) {
        ObjectAnimator animator = ObjectAnimator.ofFloat(imageView, "translationX", 0f);
        animator.setDuration(duration);
        animator.start();
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //imageView.setAlpha(0.5f);
            }
        });
    }


    @SuppressLint("CheckResult")
    private void initView() {
        ButterKnife.bind(this);
        mDownloadManager = new AppDownloadManager(this);
        for (int i = 0; i < 10; i++) {
            list.add("111");
        }
        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(this);
        rvList.setNestedScrollingEnabled(false);
        rvList.setLayoutManager(gridLayoutManager);
        demoAdapter = new DemoAdapter(this, list);
        rvList.setAdapter(demoAdapter);

        Utils.singleOnclickListener(tv_onclick, () -> {
            mLoadingImageView.setLoadingStatus(!mLoadingImageView.isLoading());
        });
    }

    private void init() {
        initView();
        //获取唤醒参数
        OpenInstall.getWakeUp(getIntent(), wakeUpAdapter);
        //携带参数安装
        OpenInstall.getInstall(new AppInstallAdapter() {
            @Override
            public void onInstall(AppData appData) {
                //获取渠道数据
                String channelCode = appData.getChannel();
                //获取自定义数据
                String bindData = appData.getData();
                Log.e("OpenInstall", "getInstall : installData = " + appData.toString());
            }
        });

        OpenInstall.reportEffectPoint("effect_test", 1);

        PwdLoginRequest pwdLoginRequest = new PwdLoginRequest("18502189235", "yf123456");
        presenter.load(pwdLoginRequest);
        appBar.addOnOffsetChangedListener(this);
//        tv_onclick.setOnClickListener(v -> {
//           mLoadingImageView.setLoadingStatus(!mLoadingImageView.isLoading());
////            moveleft(500, 40f);
////            moveAlpha(500, 1f, 0.5f);
//        });
        tvTakePhoto.setOnClickListener(v -> {
//            move0(500);
//            moveAlpha(500, 0.5f, 1f);
            PictureSelector.create(MVPActivity.this)
                    .openGallery(PictureMimeType.ofAll())//  openCamera 开相机 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(4)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.SINGLE)// 多选  PictureConfig.MULTIPLE or 单选 PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片
                    .previewVideo(true)// 是否可预览视频
                    .enablePreviewAudio(true) // 是否可播放音频
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isGif(true)// 是否显示gif图片
                    .enableCrop(false)// 是否裁剪
                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圆形裁剪
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    //.selectionMedia(selectList)// 是否传入已选图片
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .compress(true)// 是否压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .compressSavePath(ImageUtil.getCompressPath())//压缩图片自定义保存地址
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .openClickSound(true)// 是否开启点击声音
                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.rotateEnabled(true) // 裁剪是否可旋转图片
                    //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                    //.videoQuality()// 视频录制质量 0 or 1
                    //.videoSecond()//显示多少秒以内的视频or音频也可适用
                    //.recordVideoSecond()//录制视频秒数 默认60s
                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                    //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                    //.isDragFrame(false)// 是否可拖动裁剪框(固定)
                    //.compressSavePath(getPath())//压缩图片保存地址
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        });


        mDownloadManager.setUpdateListener((currentByte, totalByte) -> {
            if ((currentByte == totalByte) && totalByte != 0) {
                toast("下载完成");
            }
        });

      mDownloadManager.downloadApk("https://imtt.dd.qq.com/16891/apk/5CACCB57E3F02E46404D27ABAA85474C.apk", "11", "22");

      // mDownloadManager.installApk(this);
      //  mDownloadManager.isNewAPK(this, "1111");
    }

    @Override
    protected String showTitle() {
        return "";
    }


    @Override
    public void setData(LoginResult loginResult) {
        toast("成功");
    }

    @Override
    public void error(String error) {
        toast("错误:" + error);
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        //垂直方向偏移量
        int offset = Math.abs(verticalOffset);
        //最大偏移距离
        int scrollRange = appBarLayout.getTotalScrollRange();
        if (offset <= scrollRange / 2) {//当滑动没超过一半，展开状态下toolbar显示内容，根据收缩位置，改变透明值
            // toolbarOpen.setVisibility(View.VISIBLE);
            toolbarClose.setVisibility(View.GONE);
            //根据偏移百分比 计算透明值
            float scale2 = (float) offset / (scrollRange / 2);
            int alpha2 = (int) (255 * scale2);
            // bgToolbarOpen.setBackgroundColor(Color.argb(alpha2, 221, 75, 57));
        } else {//当滑动超过一半，收缩状态下toolbar显示内容，根据收缩位置，改变透明值
            toolbarClose.setVisibility(View.VISIBLE);
            // toolbarOpen.setVisibility(View.GONE);
            float scale3 = (float) (scrollRange - offset) / (scrollRange / 2);
            int alpha3 = (int) (255 * scale3);
            bgToolbarClose.setBackgroundColor(Color.argb(alpha3, 221, 75, 57));
        }
        //根据偏移百分比计算扫一扫布局的透明度值
        float scale = (float) offset / scrollRange;
        int alpha = (int) (255 * scale);
        bgContent.setBackgroundColor(Color.argb(alpha, 221, 75, 57));
    }


    AppWakeUpAdapter wakeUpAdapter = new AppWakeUpAdapter() {
        @Override
        public void onWakeUp(AppData appData) {
            //获取渠道数据
            String channelCode = appData.getChannel();
            //获取绑定数据
            String bindData = appData.getData();
            Log.e("OpenInstall", "getWakeUp : wakeupData = " + appData.toString());
        }
    };


    @Override
    public void onResume() {
        super.onResume();
        if (mDownloadManager != null) {
            mDownloadManager.resume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mDownloadManager != null) {
            mDownloadManager.onPause();
        }
    }

}
